/*************************************************************************
	> File Name: 1.slave.c
	> Author: Maureen 
	> Mail: 1437867946@qq.com 
	> Created Time: Sat 27 Mar 2021 06:33:55 PM CST
 ************************************************************************/

#include "head.h"

struct Config config;

int main(int argc, char **argv) {
    int pid;
    int que_id;
    //1.解析配置文件
    int opt;

    //TODO:实现缺省值
    //init_config(&config);

    //TODO: 实现get_config
    if (get_config("./slave.json", &config) < 0) {
        perror("get_config");
        exit(1);
    }

    /*if the config is not global variable，need to init.*/
    //memset(&config, 0, sizeof(config));
    //bzero(&config, sizeof(config));

    /*parse running params*/
    while ((opt = getopt(argc, argv, "n:m:p:")) != -1) {
        switch (opt) {
            case 'n':
                config.worker_size = atoi(optarg);
                break;
            case 'm':
                strcpy(config.master_ip, optarg);
                break;
            case 'p':
                config.master_port = atoi(optarg);
                break;
            default:
                fprintf(stderr, "Usage : %s -n worker_size -m master_ip -p master_port\n", argv[0]);
                exit(1);
        }
    }
    DBG("<"YELLOW"Debug"NONE"> : \n");
    DBG("<"YELLOW"===================\nConfig info:\n");
    DBG(YELLOW"master_ip = %s\n", config.master_ip);
    DBG(YELLOW"master_port = %d\n", config.master_port);
    DBG(YELLOW"worker_size = %d\n", config.worker_size);
    DBG(YELLOW"interval_cpu.time = %d\n", config.inter_time.cpu.time);
    DBG("<"YELLOW"===================\n");
    DBG("<"L_GREEN"Note"NONE"> : End of config...\n");
   

    //2.创建进程
    key_t key = ftok(".", 202103);
    if ((que_id = create_msg_queue(key)) < 0) {
        perror("create_msg_queue");
        exit(1);
    }
    DBG("<"L_GREEN"Note"NONE"> : Msg queue created successfully!\n");

    if ((pid = fork()) < 0) {
        perror("fork()");
        exit(1);
    }
    if (pid) {
        //TODO:基于配置信息，循环地发送消息到消息队列
       // send_loop()
    } else {
        DBG("<"L_GREEN"Note"NONE"> : Child process crated for system detect...\n");
        //TODO:create thread pool to get msg from msg queue

    }

    return 0;
}
